<template>
  <div class="i-table-no-border">
    <Row type="flex" justify="space-between">
      <div>
        <table-btns
          :tableTopOperateData="listData.tableTopOperate"
          :tableTopBatchOperate="listData.tableTopBatchOperate"
          :selectedData="selectedData"
          :requestApi="listData.requestApi"
          :basePath="basePath"
          @exportData="exportData"
          @actionsChange="getData"
        >
        </table-btns>
      </div>
      <Row type="flex">
        <Upload
          v-show="showBtn('批量新增')"
          :show-upload-list="false"
          :format="['xlsx', 'xls', 'csv']"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-format-error="handleUploadFormatError"
          :before-upload="handleBeforeUpload"
          :action="`${uploadBaseURL}sysback/template/producttemplateattrvalue/insertByExcel`"
          ><Button
            class="ivu-mr-8"
            type="primary"
            icon="ios-add-circle-outline"
            >批量新增</Button
          ></Upload
          >
        <Button
          class="ivu-mr-8"
          type="primary"
          icon="ios-download-outline"
          :loading="exportLoading"
          @click="handleExportData"
        >模板导出</Button
        >
      </Row>
    </Row>
    <!-- 表格内容 start  -->
    <Table
      ref="table"
      :columns="columns"
      :data="tableDataList"
      :loading="loading"
      height='500'
      class="ivu-mt"
      stripe
      @on-filter-change="handleFilterChange"
      @on-select="handleSelect"
      @on-select-cancel="handleSelectCancel"
      @on-select-all="handleSelectAll"
      @on-select-all-cancel="handleSelectAllCancel"
    >
      <template slot-scope="{ row }" slot="auditState">
        <span v-if="row.auditState === '0'">待审核</span>
        <span v-if="row.auditState === '1'">审核不通过</span>
        <span v-if="row.auditState === '2'">审核通过</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <table-actions
          :requestApi="listData.requestApi"
          :basePath="basePath"
          :rowData="row"
          :indexData="index"
          @actionsChange="getData"
        ></table-actions>
      </template>
    </Table>
    <!-- 表格内容 end  -->
    <!-- 分页 start  -->
    <div class="ivu-mt ivu-text-center">
      <Page
        :total="totalNum"
        show-total
        show-sizer
        transfer
        :current.sync="nowPage"
        @on-change="getData"
        @on-page-size-change="handleChangePage"
      />
    </div>
    <!-- 分页 end  -->
  </div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex';
import util from '@/libs/util';
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import tables from '@/mixins/dynamictable'; // 混入通用代码

import qwInput from '@/components/common/formItem/qwInput'; // 表单input组件
import qwSelect from '@/components/common/formItem/qwSelect'; // 表单select组件
import qwDatePicker from '@/components/common/formItem/qwDatePicker'; // 表单日期组件
import qwSelectTree from '@/components/common/formItem/qwSelectTree'; // 表单下拉树组件

import tableActions from './tableActions'; // 表格操作项
import tableBtns from './tableBtns'; // 表格内部操作按钮

export default {
  mixins: [tables],
  props: {
    dynamicData: {
      type: Object
    },
    pagePath: {
      type: String
    }
  },
  computed: {
    ...mapState('admin/baseList', [
      'listData',
      'searchFormData',
      'searchFormDataQ'
    ]),
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  components: {
    qwInput,
    qwSelect,
    qwDatePicker,
    qwSelectTree,
    tableActions,
    tableBtns
  },
  data () {
    return {
      util: util,
      basePath: this.dynamicData.basePath, // 拼接基础路径
      exportLoading: false
    };
  },
  created () {},
  methods: {
    ...mapMutations('admin/baseList', ['setTableRowData']),
    /* 导出模板事件 */
    handleExportData () {
      this.exportLoading = true;
      ApiRequestExportTable(
        '/sysback/template/producttemplateattrvalue/excelTemplate',
        'get',
      ).then((res) => {
        this.exportLoading = false;
        const blob = new Blob([res], {
          type: 'application/octet-stream'
        });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '新增属性值.xlsx';
        link.click();
        window.URL.revokeObjectURL(blob); // 释放掉blob对象
        this.$message.success('导出成功');
      }).catch(() => {
        this.exportLoading = false;
        this.$message.error('导出失败');
      });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.loading = false;
      this.$message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.loading = true;
      this.tableData = [];
    },
    /* 上传成功 */
    handleUploadSuccess (res) {
      this.loading = false;
      if (res.retStatus !== '1') {
        return this.$message.error(res.retMessage);
      }
      this.$message.success('批量新增成功');
      this.getData(); // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
    },
    /* 上传失败 */
    handleUploadError () {
      this.loading = false;
      this.$message.error('上传失败');
    },
    // 获取表格的数据
    getData () {
      this.selectedData = [];
      let searchParam = [];
      Object.keys(this.searchFormData).forEach((key) => {
        searchParam.push({ name: key, value: this.searchFormData[key] });
      });
      Object.keys(this.searchFormDataQ).forEach((key) => {
        searchParam.push({ name: key, value: this.searchFormDataQ[key] });
      });

      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      };

      this.loading = true;
      // 开始请求列表
      ApiRequest(
        this.listData.requestApi.getTableList.url,
        this.listData.requestApi.getTableList.type,
        data
      ).then((res) => {
        let rData = res;
        if (rData.retData !== '') {
          rData.retData = rData.retData;
        }

        let tableDataList = rData.retData.results;
        tableDataList.forEach((item) => {
          let actions = [];
          actions.push(
            {
              name: 'Edit',
              label: '编辑',
              params: ['uuid', 'categoryUuid'],
              handleType: 'link'
            },
            {
              name: 'delete',
              label: '删除',
              handleType: 'alert'
            }
          );

          item.actions = actions;
        });
        // 增加表格操作项
        this.tableDataList = rData.retData.results;
        this.totalNum = rData.retData.totalNum;
        this.loading = false;
      });
    }
  }
};
</script>
<style lang="less" scoped>
.i-table-no-border .ivu-table-header th {
  background: #f8f8f8;
}
</style>
